package com.logicbus.redis.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.Pair;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.redis.client.Client;
import com.logicbus.redis.toolkit.InfoTool;

import java.util.ArrayList;
import java.util.List;

/**
 *  扫描redis信息项
 */
public class RedisInfoScan extends Segment {
    protected String pid = "$redis-client";
    protected String keyId = "$key";
    protected String valueId = "$value";
    protected String $section = "all";
    public RedisInfoScan(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        keyId = PropertiesConstants.getString(p,"keyId",keyId);
        valueId = PropertiesConstants.getString(p,"valueId",valueId);
        $section = PropertiesConstants.getString(p,"section",$section);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        Client client = ctx.getObject(pid);
        if (client != null){
            InfoTool infoTool = (InfoTool) client.getToolKit(InfoTool.class);
            List<Pair<String,String>> result = new ArrayList<Pair<String,String>>();
            infoTool.info(PropertiesConstants.transform(ctx,$section,"all"),result);
            for (Pair<String,String> p:result){
                ctx.SetValue(keyId,p.key());
                ctx.SetValue(valueId,p.value());
                super.onExecute(root,current,ctx,watcher);
            }
        }
    }
}
